#!/usr/bin/env python

# Copyright © Michal Čihař <michal@weblate.org>
#
# SPDX-License-Identifier: GPL-3.0-or-later

import re
import subprocess
import sys
from pathlib import Path

import requests
from ruamel.yaml import YAML

if len(sys.argv) != 2:
    print("Usage: ./scripts/set-version.py VERSION")
    sys.exit(1)

version = version_full = sys.argv[1]
if version.count(".") == 1:
    version_full = f"{version}.0"


def replace_file(name: str, search: str, replace: str) -> None:
    content = Path(name).read_text(encoding="utf-8")

    content = re.sub(search, replace, content, flags=re.MULTILINE)
    Path(name).write_text(content, encoding="utf-8")


def prepend_file(name: str, content: str) -> None:
    content += Path(name).read_text(encoding="utf-8")
    Path(name).write_text(content, encoding="utf-8")


yaml = YAML()
config = yaml.load(Path("~/.config/hub").expanduser().read_text(encoding="utf-8"))

# Get/create milestone
milestones_api = "https://api.github.com/repos/WeblateOrg/weblate/milestones"
api_auth = f"token {config['github.com'][0]['oauth_token']}"
headers = {"Authorization": api_auth, "Accept": "application/vnd.github.v3+json"}
response = requests.get(
    milestones_api, headers=headers, timeout=1, params={"state": "open"}
)
response.raise_for_status()
milestone_url = None
for milestone in response.json():
    if milestone["title"] == version:
        milestone_url = milestone["html_url"]

if milestone_url is None:
    response = requests.post(
        milestones_api, headers=headers, json={"title": version}, timeout=1
    )
    payload = response.json()
    try:
        milestone_url = payload["html_url"]
    except KeyError:
        print(payload)
        raise

# Set version in the files
replace_file("weblate/utils/version.py", "^VERSION =.*", f'VERSION = "{version}-dev"')
replace_file("docs/conf.py", "release =.*", f'release = "{version}"')
replace_file("pyproject.toml", "^version = .*", f'version = "{version}"')
replace_file(
    "client/package.json", '  "version": ".*",', f'  "version": "{version_full}",'
)

# Update changelog
title = f"Weblate {version}"
underline = "-" * len(title)
header = f"""{title}
{underline}

*Not yet released.*

.. rubric:: New features

.. rubric:: Improvements

.. rubric:: Bug fixes

.. rubric:: Compatibility

.. rubric:: Upgrading

Please follow :ref:`generic-upgrade-instructions` in order to perform update.

.. rubric:: Contributors

.. include:: changes/contributors/{version}.rst

`All changes in detail <{milestone_url}?closed=1>`__.

"""
prepend_file("docs/changes.rst", header)
version_contributors = Path("docs") / "changes" / "contributors" / f"{version}.rst"
version_contributors.write_text("""..
   DO NOT EDIT! Automatically generated by scripts/prepare-release upon release.
""")

files = [
    "weblate/utils/version.py",
    "docs/conf.py",
    "docs/changes.rst",
    "pyproject.toml",
    "client/package.json",
    "uv.lock",
    version_contributors.as_posix(),
]
subprocess.run(["git", "add", version_contributors.as_posix()], check=True)
subprocess.run(
    [
        "uv",
        "run",
        "--only-group",
        "pre-commit",
        "pre-commit",
        "run",
        "--files",
        *files,
    ],
    check=False,
)
subprocess.run(
    ["git", "commit", "-m", f"chore: setting version to {version}", *files], check=True
)
